// pages/search/search.js
var app = getApp();
var util=require("../../utils/util");
const home = require("../../api/home");
var len = 5;

Page({
  // 页面的初始数据
  data: {
    word: '',
    list: [],
    hot_list: [],
    token: ''
  },
  //  生命周期函数--监听页面加载
  onLoad: function (options) {
    var that = this;
    wx.getStorage({
      key: 'token',
      success:function(res){
        that.setData({token:res.data})
        that.get_near_nearch(res.data)
      },
      fail:function(){
        wx.getStorage({
          key: 'history',
          success: function(res) {
            that.setData({list: res.data})
          },
        })
      }
    })
    that.get_hot_search();
  },
  // 
  search_val:function(e){
    this.setData({ word: e.detail.value })
  },
  // 搜索判断
  search_word:function(e){
    var that = this,testSpace = /^[ ]*$/g;
    var word = e.currentTarget.dataset.word ? e.currentTarget.dataset.word : that.data.word;
    that.setData({word: word})
    if(!word||testSpace.test(word)){
      util.page_show_toast('请输入关键字搜索',1500);
    }else{
      word=util.removeAllSpace(word)
      wx.getStorage({
        key: 'history',
        success: function (res) {
          var arr = res.data;
          if(arr.length < len){
            if (arr.indexOf(word) == -1){
              arr.push(word)
            }
          } else if (arr.length == len){
            if (arr.indexOf(word) == -1) {
              arr.pop()
              arr.unshift(word)
            }
          }
          wx.setStorageSync('history', arr)
        },
        fail: function(res){
          var arr = [];
          arr.push(word);
          wx.setStorageSync('history', arr)
        }
      })
      wx.redirectTo({
        url: '../searchlist/searchlist?name=' + word,
      })
    }
  },
  // 清除历史
  clear_history:function(){
    var that=this,token=that.data.token,list=that.data.list,arr=[];
    if(list.length>0){
      if(token){
        for(var i=0;i<list.length;i++){
          arr.push(list[i].id)
        }
        var ids=arr.join(",")
        that.del_search(ids)
      }else{
        wx.removeStorageSync('history');
      }
      this.setData({ list: [] })
    }else{
      util.page_show_toast('无历史信息',2000)
    }
  },
  // 热门搜索
  get_hot_search:function(){
    wx.showLoading({title: '加载中'})
    var that=this;
    home.get_hot_search().then(res=>{
      if(res.data.code==200){
        var list=res.data.data;
        that.setData({hot_list:list})
      }
    })
  },
  // 最近搜索
  get_near_nearch:function(token){
    var that=this;
    home.get_near_nearch(token).then(res=>{
      if(res.data.code==200){
        var list=res.data.data;
        that.setData({list:list});
        wx.setStorageSync('search_list', list)
      }
    })
  },
  // 删除最近搜索
  del_search:function(ids){
    var that=this,token=that.data.token;
    home.del_search({"ids":ids},token).then(res=>{

    })
  },
})